//
//  AlibcUtil.m
//  ios
//
//  Created by xgz on 2020/11/20.
//

#import "AlibcUtil.h"
#import <AlibcTradeUltimateSDK/AlibcTradeUltimateSDK.h>
// 媒体电商套件图片库协议实现
#import "ALITradeDemoImageLoader.h"
#import <WindmillWeaver/WMLHandlerFactory.h>

// 电商套件外跳媒体页面实现
#import "ALiTradeDemoURLHandler.h"
#import <AlibcTradeContainer/AlibcTradeMiniAppURLRouter.h>

#import "ALITradeDemoZipArchiver.h"


//
@interface AlibcUtil()
// 图片库实现
@property (nonatomic,strong)ALITradeDemoImageLoader *imageLoaderImp;

// 外跳路由协议实现
@property (nonatomic,strong)ALiTradeDemoURLHandler *urlHandlerImp;

@end
@implementation AlibcUtil



static AlibcUtil *p = nil ;
+(instancetype)shared{
    if(p == nil){
        p = [[AlibcUtil alloc]init];
    }
    return p;
}

//初始化百川
- (void)initAlibc:(FlutterResult)result{
    [[AlibcTradeUltimateSDK sharedInstance] setDebugLogOpen:YES];
    __weak typeof(self) weakSelf = self;
    [[AlibcTradeUltimateSDK sharedInstance] asyncInitWithSuccess:^{
            NSLog(@"初始化百川成功");
        result(@{@"status":@(true),@"code":@(0),@"msg":@"succ"});
        __strong typeof(self) self = weakSelf;
        
        // 注册Zip解压能力
        [WMLHandlerFactory registerHandler:[ALITradeDemoZipArchiver new] withProtocol:@protocol(TRVZipArchiveProtocol)];
        
        // 注册图片库协议
        self.imageLoaderImp = [ALITradeDemoImageLoader new];
        [WMLHandlerFactory registerHandler:self.imageLoaderImp withProtocol:@protocol(WMLImageLoaderProtocol)];
        
        // 注册电商套件外跳媒体路由协议实现
        self.urlHandlerImp = [ALiTradeDemoURLHandler new];
        [[AlibcTradeMiniAppURLRouter sharedInstance] addMiniAppRouterListener:self.urlHandlerImp];
        
#ifdef DEBUG
         //必须在百川初始化成功之后调用，开启自检工具的悬浮入口
         [[AlibcTradeUltimateSDK sharedInstance] enableAutoShowDebug:YES];
#endif
        } failure:^(NSError * _Nonnull error) {
            NSLog(@"初始化百川失败");
            
            result(@{@"status":@(error.code),@"code":@(error.code),@"msg":error.userInfo});
        
        }];
}

///是否登录
- (void)isLogin:(FlutterResult)result{
    bool isLogin = [[[AlibcTradeUltimateSDK sharedInstance] loginService] isLogin];

    result(@{
        @"status":@(isLogin),
        @"msg": isLogin? @"已登录":@"未登录",
        @"isLogin":@(isLogin)
           }
           );
}
///去登录
- (void)showLogin:(FlutterResult)result{
    UINavigationController *nav = (UINavigationController*)[UIApplication sharedApplication].keyWindow.rootViewController;
    [[[AlibcTradeUltimateSDK sharedInstance] loginService] auth:nav success:^(AlibcUser *user) {
        result(@{
            @"status":@true,
            @"msg": @"登录成功",
            @"userInfo":@{
                    @"userId":user.openId,@"userNick":user.nick
            },
               }
               );
        } failure:^(NSError *error) {
            result(@{
                @"status":@false,
                @"msg": @"登录失败",
                @"code":@(1),
                @"userInfo":@{
                        @"userId":@"",@"userNick":@""
                },
                   }
                   );
        }];
}

///打开电商套件
- (void)openTradePageByCode:(FlutterMethodCall*)call result:(FlutterResult)result{
    
    NSString *suiteCode = call.arguments[@"suiteCode"];

    AlibcTradeUrlParams *urlParams = [self coverMapToAlibcTradeUrlParams:call.arguments[@"bizParams"]];
    
    AlibcTradeShowParams *showParams = [self coverMapToAlibcTradeShowParams:call.arguments[@"showParams"]];
    
    AlibcTradeTaokeParams *taokeParam = [self coverMapToAlibcTradeTaokeParams:call.arguments[@"taokeParams"]];
    
    NSDictionary *trackParam = [call.arguments[@"trackParams"] isKindOfClass:[NSNull class]]? @{}:call.arguments[@"trackParams"];
    
    
    UINavigationController *nav = (UINavigationController*)[UIApplication sharedApplication].keyWindow.rootViewController;
    [[AlibcTradeUltimateSDK sharedInstance].tradeService
        openTradePageByCode:suiteCode
     parentController:nav
                  urlParams:urlParams
                 showParams:showParams
                taoKeParams:taokeParam
                 trackParam:trackParam
            openUrlCallBack:^(NSError *_Nonnull error) {
              if (error) {
                  NSLog(@"调用失败");
                  result(@{@"status":@(error.code),@"code":@(error.code),@"msg":error.userInfo});
              } else {
                  NSLog(@"调用成功");
                  result(@{@"status":@(true),@"code":@(0),@"msg":@"succ"});
              }
            }];
    
}
///打开商品页面
- (void)openTradePageByUrl:(FlutterMethodCall*)call result:(FlutterResult)result{
    
    NSLog(@"%@",call.arguments);
    NSString *detailUrl = call.arguments[@"detailUrl"];
    NSDictionary *showParamsDic = call.arguments[@"showParams"];
    AlibcTradeShowParams *showParams = [self coverMapToAlibcTradeShowParams:call.arguments[@"showParams"]];
    
    AlibcTradeTaokeParams *taokeParam = [self coverMapToAlibcTradeTaokeParams:call.arguments[@"taokeParams"]];
    
    NSDictionary *trackParams = [call.arguments[@"trackParams"] isKindOfClass:[NSNull class]]? @{}:call.arguments[@"trackParams"];
    
    // 构造taokeParam
    [[[AlibcTradeUltimateSDK sharedInstance] tradeService] openTradeUrl:detailUrl parentController:(UINavigationController*)[UIApplication sharedApplication].keyWindow.rootViewController showParams:showParams taoKeParams:taokeParam trackParam:trackParams openUrlCallBack:^(NSError *error) {
        if (error) {
            NSLog(@"调用成功");
        } else {
            NSLog(@"调用失败");
        }
    }];
   
}
- (AlibcTradeUrlParams*)coverMapToAlibcTradeUrlParams:(NSDictionary *)dic{
    AlibcTradeUrlParams *params = [AlibcTradeUrlParams new];
    params.id = [self getParams:@"id" dic:dic];
    params.shopId = [self getParams:@"shopId" dic:dic];
    params.bizExtMap = [dic[@"extParams"] isKindOfClass:[NSNull class]]? nil:dic[@"extParams"];
    return params;
}
- (AlibcTradeTaokeParams*)coverMapToAlibcTradeTaokeParams:(NSDictionary *)dic{
    AlibcTradeTaokeParams *params = [AlibcTradeTaokeParams new];
    params.pid = [self getParams:@"pid" dic:dic];
    params.subPid = [self getParams:@"subPid" dic:dic];
    params.relationId = [self getParams:@"relationId" dic:dic];
    params.unionId = [self getParams:@"unionId" dic:dic];
    params.materialSourceUrl = [self getParams:@"materialSourceUrl" dic:dic];
    params.extParams = [dic[@"extParams"] isKindOfClass:[NSNull class]]? nil:dic[@"extParams"];
    return params;
}
- (AlibcTradeShowParams*)coverMapToAlibcTradeShowParams:(NSDictionary *)dic{
    AlibcTradeShowParams *params = [AlibcTradeShowParams new];
    params.linkKey = [self getParams:@"backUrl" dic:dic];
    params.degradeUrl = [self getParams:@"degradeUrl" dic:dic];
    return params;
}
- (NSString*)getParams:(NSString*)key dic:(NSDictionary*)dic{
    if([dic[key] isKindOfClass:[NSNull class]]){
        return @"";
    }else{
        return dic[key];
    }
}
@end
